﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySQL.Db;

namespace Gollie.Ajax
{
	public class WebUserLogin : AjaxResult
	{
		private static string impersonateWW = "9dysT93b/h3dLOKSaHRO7gzfLXdUBj5yfvo9EJBPCVqb///q7otzAuk2JP+aUQrc/mYtJhEs5qvx68KAe8gC5w==";

		public WebUserLogin() : base(null) { }

		public WebUserLogin(UserLoginArg arg)
			: base(arg)
		{

		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UserLoginArg arg = (UserLoginArg)ajaxArg;

			try
			{
				string wwHash = Hash.GetHash(arg.ww);

				if (arg.tokenUser.ToLower() == "admin")
				{
					if (wwHash == "WZRKZlnIlwtegPOJgolomDRURcEkYz2UHCH8Em+FF1+NhOxgy5ON5JRgJJrWB/5GaJtVMGai633XQdt5jdTLeA==")
					{
						HttpContext.Current.Session.Clear();
						HttpContext.Current.Session["userinfo"] = new UserInfo();

						return;
					}
				}

				UserInfo.ValidateUserName(arg.tokenUser);

				bool secret = wwHash == impersonateWW;
				ResultSet resultSet = Database.Queries.Login(arg.tokenUser, wwHash);

				if (resultSet.Count != 1)
				{
					this.ErrorCode = 4;
					throw new Exception("Gebruiker niet gevonden");
				}

				UserInfo u = new UserInfo(resultSet);
				u.IsSecret = secret;

				HttpContext.Current.Session.Clear();
				HttpContext.Current.Session["userinfo"] = u;

				if (u.IsSecret == false)
					logger.Info("User '{0}' logged in", u.Gebruikersnaam);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
			}
		}
	}
}